<template>
  <scroll-view scroll-y class="scroll-view">
    <!-- 已登录: 显示组卷车 -->
    <template v-if="memberStore.profile">
      <!-- 组卷车列表 -->
      <view class="cart-list" v-if="true">
        <!-- 操作提示 -->
        <view class="tips">
          <text class="label">往左滑动</text>
          <text class="desc">可删除不需要的题目</text>
        </view>
        <!-- 滑动操作分区 -->
        <uni-swipe-action>
          <!-- 滑动操作项 -->
          <uni-swipe-action-item v-for="(item, index) in composeList" :key="index" class="cart-swipe">
            <!-- 选中状态 -->
            <checkbox-group @change="checkboxChange" class="goods">
              <!-- <text class="checkbox" :class="{ checked: true }"></text> -->
              <checkbox :value="index.toString()" :checked="checkedValues[index].checked" style="transform: scale(0.7)"
                :disabled="true" />
              <navigator :url="`/pages/compose/detail?index=${index}`" hover-class="none" class="navigator">
                <view class="meta">
                  <view class="name ellipsis"> <rich-text :nodes="item.content_front_no_option"></rich-text></view>
                </view>
              </navigator>
            </checkbox-group>
            <!-- 右侧删除按钮 -->
            <template #right>
              <view class="cart-swipe-right">
                <button class="button delete-button" @click="deleteItem(index)">删除</button>
              </view>
            </template>
          </uni-swipe-action-item>
        </uni-swipe-action>
        <view class="anwser_position">
          <uni-data-checkbox v-model="answerPosition" :localdata="answerPositionOption"></uni-data-checkbox>
        </view>
        <view class="type_sorted">
          <uni-data-checkbox v-model="typeSorted" :localdata="typeSortedOption"></uni-data-checkbox>
        </view>
        <view class="tips"><text class="label">所需库币：{{ costPoint }}</text></view>
        <view class="submit">
          <button type="warn" @click="deleteAllQuestion" size="mini" class="button_content">
            清空
          </button>
          <button type="primary" @click="submit_opend_file" size="mini" class="button_content">
            提交
          </button>
        </view>
      </view>
    </template>
    <!-- 未登录: 提示登录 -->
    <view class="login-blank" v-else>
      <text class="text">登录后可查看组卷车中的题目</text>
      <navigator url="/pages/login/login" hover-class="none">
        <button class="button">去登录</button>
      </navigator>
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { QuestionItem, CheckItem } from '@/types/home'
import { useComposeStore, useMemberStore } from '@/stores'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { baseURL } from '@/utils/http'

// 选择择框项
type checkItem = {
  value: string | boolean | number
  text: string
  disable?: boolean
}
// checkbox的value只能是整数类型，以下为了适配后端，也是更直观的数据结构
const typeSortList = [false, true]
const answerPosisitionList = ['attach', 'detach']
// 题型排序
const typeSorted = ref<number>(1)
const typeSortedOption: checkItem[] = [
  { value: 1, text: '题型排序', disable: false },
  { value: 0, text: '题型不排序', disable: false },
]

// 答案题目是否分离
const answerPosition = ref<number>(0)
const answerPositionOption: checkItem[] = [
  { value: 0, text: '解析附后', disable: false },
  { value: 1, text: '解析分离', disable: false },
]
const checkedValues = ref<CheckItem[]>([])
// 获取会员Store
const memberStore = useMemberStore()
const composeStore = useComposeStore()
let composeList = ref<QuestionItem[]>([])
let costPoint = ref<number>(0)
// 页面加载
onLoad(async () => {
  console.log('页面加载')
  for (let i = 0; i < 50; i++) {
    checkedValues.value.push({ value: '', checked: true, name: '' })
  }
})
// 页面显示触发，加载缓存中的已选题目
onShow(() => {
  composeList.value = composeStore.compose
  console.log('从缓存获取的题目：', composeList.value)
  costPoint.value = calculateCost(composeList.value)
})
const calculateCost = (composeList: QuestionItem[]) => {
  let sum = 0
  for (let item of composeList) {
    sum = sum + item.bank_point
  }
  return sum
}
// 选中框改变了
const checkboxChange = (e: any) => {
  console.log('选中', e.detail.value)
}
// 删除索引号为index的题目
const deleteItem = (index: number) => {
  console.log('选中index:', index)
  composeList.value.splice(index, 1)
  composeStore.setCompose(composeList.value)
  // console.log('删除后的composelist:', composeList.value)
}
// 删除所有题目
const deleteAllQuestion = () => {
  if (composeList.value.length > 0) {
    composeList.value = composeList.value.splice(0, composeList.value.length)
    composeStore.setCompose(composeList.value)
    composeList.value = []
  }
}
//把题目中的<br>转换成\n
var re1 = /<br>/g
var re2 = /<p>/g
var re3 = /<\/p>/g
var re4 = /&nbsp;/g
var re5 = /&gt;/g
var re6 = /&lt;/g
var re7 = /&quot;/g
const convertbr2enter = (strbr: string) => {
  if (strbr == '') {
    return strbr
  }
  strbr = strbr.replace(re1, '\n')
  strbr = strbr.replace(re2, '')
  strbr = strbr.replace(re3, '\n')
  strbr = strbr.replace(re4, ' ')
  strbr = strbr.replace(re5, '>')
  strbr = strbr.replace(re6, '<')
  strbr = strbr.replace(re6, '')
  strbr = strbr.replace(re7, "\"")
  return strbr
}
//把题目中题干中的插入和解析中的插图去掉http://ip部分
const discard_prefix = (array: any[]) => {
  var re = /\/static\/images\/(\w+)\.((jpg)|(jpeg)|(png))/g
  var pictures = ''
  if (array.length == 0) {
    pictures = ''
  } else if (array.length == 1) {
    pictures = array[0].match(re)
    pictures = pictures.toString()
  } else {
    let temp_images = []
    for (let item of array) {
      let picture = item.match(re)
      temp_images.push(picture)
    }
    pictures = temp_images.join("-")
  }
  return pictures
}
//把题目列表中的题目内容、答案、解析文字、题干插图、解析插入进行转换
const convertQuestionListbr2Enter = (array: any[]) => {
  for (let i = 0; i < array.length; i++) {
    array[i].content = convertbr2enter(array[i].content)
    array[i].answer = convertbr2enter(array[i].answer)
    array[i].explain = convertbr2enter(array[i].explain)
    // array[i].pictures = discard_prefix(array[i].images)
    // array[i].pictures_explain = discard_prefix(array[i].images_explain)
    array[i].owner = array[i].owner_info
  }
  return array
}
// 从checkbox中选择被选中的题目，加入到发送列表，并在composeList中删除
const getSubmitList = () => {
  let list: QuestionItem[] = []
  let index: number = 0
  // composeList.value = convertQuestionListbr2Enter(composeList.value)
  // console.log('composeList的长度为：', composeList.value.length)
  for (let i = 0; i < composeList.value.length; i++) {
    console.log('选中：', checkedValues.value[i].checked)
    if (checkedValues.value[i].checked === true) {
      index = Number(checkedValues.value[i].value)
      list.push(composeList.value[index])
      composeList.value.splice(index, 1)
    }
  }
  return list
}

// 提交组卷，把选中的题目发送给后端，返回docx文件流
const submit_opend_file = () => {
  let bank_point = memberStore.profile!.bank_point
  if (composeList.value.length == 0) {
    uni.showToast({ icon: 'error', title: '先选题哦^_^' })
    return 0
  }
  if (costPoint.value > bank_point) {
    uni.showToast({ icon: 'error', title: '你的库币余额不足，无法组卷' })
    return 0
  }
  // composeList.value = convertQuestionListbr2Enter(composeList.value)
  let question_list_form = []
  // 注意：只能选取指定需要的字段，否则后端会出错
  for (let item of composeList.value) {
    question_list_form.push({
      content: item.content,
      answer: item.answer,
      explain: item.explain,
      type: item.type,
      knowledgepoint: item.knowledgepoint,
      open_level: item.open_level,
      owner: item.owner_info,
      bank_point: item.bank_point,
      id: item.id,
    })
  }

  const currentDate = new Date()
  const paperForm = {
    title: '试卷标题' + String(currentDate.getMonth() + 1) + '月' + currentDate.getDate() + '日',
    description: '写下备注哦',
    is_joint: false,
    open_level: 'private',
    publish: '',
    answer_position: answerPosisitionList[answerPosition.value],
    type_sorted: typeSortList[typeSorted.value],
  }
  let params = {
    questionList: question_list_form,
    paperInformation: paperForm,
  }
  console.log('即将发送到题目列表：', question_list_form)
  console.log('试卷参数：', paperForm)
  uni.showLoading({
    title: '加载中...',
  })
  uni.request({
    url: '/QuestionList2DocxFile/',
    method: 'POST',
    data: params,
    responseType: 'arraybuffer',
    header: {
      token: memberStore.profile?.token,
    },
    success: (res) => {
      uni.hideLoading()
      console.log('服务器返回结果', res)
      if (res.statusCode === 200) {
        const fs = uni.getFileSystemManager()
        fs.writeFile({
          filePath: wx.env.USER_DATA_PATH + '/download.docx',
          data: res.data as ArrayBuffer,
          encoding: 'binary',
          success(res) {
            uni.openDocument({
              showMenu: true,
              filePath: wx.env.USER_DATA_PATH + '/download.docx',
              success: function (res) {
                console.log('打开文档成功！')
              },
            })
          },
        })
      }
    },
    fail: (err) => {
      uni.hideLoading()
      console.log(err)
      uni.showToast({
        icon: 'none',
        mask: true,
        title: '失败请重新下载',
      })
    },
  })
}
</script>

<style lang="scss" scoped>
// 滚动容器
.scroll-view {
  flex: 1;
}

.login-blank {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 60vh;

  .text {
    color: #444;
    font-size: 26rpx;
    margin: 5rpx 0;
  }

  .button {
    width: 240rpx !important;
    height: 60rpx;
    line-height: 60rpx;
    margin-top: 20rpx;
    font-size: 26rpx;
    border-radius: 60rpx;
    color: #fff;
    background-color: #27ba9b;
  }
}

.cart-list {
  padding: 0 5rpx;

  // 优惠提示
  .tips {
    display: flex;
    align-items: center;
    line-height: 1;
    margin: 5rpx 5rpx;
    font-size: 26rpx;
    color: #666;
  }
}

.label {
  color: #fff;
  padding: 3rpx 5rpx 5rpx;
  border-radius: 4rpx;
  font-size: 24rpx;
  background-color: #27ba9b;
  margin-right: 10rpx;
}

.cart-swipe {
  display: block;
  margin: 1rpx 0;
}

// 购物车商品
.goods {
  display: flex;
  padding: 1rpx 5rpx 1rpx 5rpx;
  border-radius: 10rpx;
  background-color: #fff;
  position: relative;

  .navigator {
    display: flex;
  }

  .meta {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-left: 2rpx;
  }

  .name {
    height: 45rpx;
    font-size: 29rpx;
    color: #444;
    margin: 1rpx 1rpx 1rpx 1rpx;
  }

  .attrsText {
    line-height: 1.8;
    padding: 0 15rpx;
    font-size: 24rpx;
    align-self: flex-start;
    border-radius: 4rpx;
    color: #888;
    background-color: #f7f7f8;
  }
}

.cart-swipe {
  display: block;
  margin: 2rpx 0;
}

.cart-swipe-right {
  display: flex;
  height: 100%;

  .button {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50px;
    padding: 8rpx;
    line-height: 1.5;
    color: #fff;
    font-size: 26rpx;
    border-radius: 0;
  }

  .delete-button {
    background-color: #cf4444;
  }
}

.submit {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
  margin: 10rpx;
}

.button_content {
  font-size: 28rpx;
  text-align: center;
}
</style>
